package com.ian.departmentmanager.service.Impl;

import java.io.File;

import javax.mail.internet.MimeMessage;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.ian.departmentmanager.service.MailService;

public class MailServiceImpl implements MailService {

	private JavaMailSender sender;

	public void setSender(JavaMailSender sender) {
		this.sender = sender;
	}

	@Override
	public String sendMail(String sendFrom, String sendTo, String title,
			String attachFile, String content) {
		// 设定mail server
		((JavaMailSenderImpl) sender).setHost("smtp.163.com");
		((JavaMailSenderImpl) sender).setUsername("gexinyan1987");
		((JavaMailSenderImpl) sender).setPassword("272544123");

		MimeMessage mailMessage = sender.createMimeMessage();
		try {
			MimeMessageHelper messageHelper = new MimeMessageHelper(
					mailMessage, true, "utf-8");

			// 设置收件人，寄件人
			messageHelper.setTo(sendTo);
			messageHelper.setFrom(sendFrom);
			messageHelper.setSubject(title);
			messageHelper.setText(content, true);

			FileSystemResource file = new FileSystemResource(new File(
					attachFile));
			String a[] = attachFile.split("\\\\");
			String attachFileCNName = javax.mail.internet.MimeUtility
					.encodeWord(a[a.length-1]);
			messageHelper.addAttachment(attachFileCNName, file);
		} catch (Exception e) {
			return "邮件发送失败！";
		}
		sender.send(mailMessage);

		return "邮件发送成功";
	}

	@Override
	public String sendMail(String sendFrom, String sendTo, String title,
			String content) {
		// 设定mail server
		((JavaMailSenderImpl) sender).setHost("smtp.163.com");
		((JavaMailSenderImpl) sender).setUsername("gexinyan1987");
		((JavaMailSenderImpl) sender).setPassword("272544123");

		MimeMessage mailMessage = sender.createMimeMessage();
		try {
			MimeMessageHelper messageHelper = new MimeMessageHelper(
					mailMessage, true, "utf-8");

			// 设置收件人，寄件人
			messageHelper.setTo(sendTo);
			messageHelper.setFrom(sendFrom);
			messageHelper.setSubject(title);
			messageHelper.setText(content, true);

		} catch (Exception e) {
			return "邮件发送失败！";
		}
		sender.send(mailMessage);

		return "邮件发送成功";
	}

}
